<script lang="ts" setup>
import type { BrandVariants } from '@fluentui/tokens';

import { computed } from 'vue';

import { useAntdDesignTokens } from '@vben/hooks';
import { preferences, usePreferences } from '@vben/preferences';

// import { createDarkTheme, createHighContrastTheme,createLightTheme,createTeamsDarkTheme } from '@fluentui/tokens';
import {
  createDarkTheme,
  createLightTheme,
  teamsDarkTheme,
} from '@fluentui/tokens';
import { setTheme } from '@fluentui/web-components';
import { App, ConfigProvider, theme } from 'ant-design-vue';

import { antdLocale } from '#/locales';

import GlobalDialog from './components/global-dialog';
import { adjustBrightness, hslToColor } from './utils/color';

defineOptions({ name: 'App' });

const { tokens } = useAntdDesignTokens();

const tokenTheme = computed(() => {
  const algorithm = isDark.value
    ? [theme.darkAlgorithm]
    : [theme.defaultAlgorithm];

  // antd 紧凑模式算法
  if (preferences.app.compact) {
    algorithm.push(theme.compactAlgorithm);
  }

  return {
    algorithm,
    token: tokens,
  };
});

const appProvider = ref<HTMLElement>();
const { isDark } = usePreferences();

function updateTheme(createTheme: typeof createLightTheme) {
  // console.log(typeof tokens.colorPrimary);
  // console.log(tokens.colorPrimary);
  // console.log(tokens.colorPrimary);
  // console.log(tokens.colorTextBase);
  // // theme.colorNeutralForeground1 = tokens.colorTextBase;
  // // theme.colorNeutralForeground2 = tokens.colorTextBase;
  // theme.colorBrandBackground = tokens.colorPrimary;
  // theme.colorBrandBackgroundHover = tokens.colorPrimary;
  // theme.colorCompoundBrandStroke = tokens.colorPrimary;
  // // theme.colorBrandBackground2 = tokens.colorBgBase;
  // // theme.colorBrandBackground2Hover = tokens.colorPrimary;
  console.log(teamsDarkTheme.colorBrandBackground);

  setTheme(
    createTheme(
      new Proxy(tokens, {
        get: (_, prop) => {
          // console.log(prop);
          const color = hslToColor(tokens.colorPrimary);
          const key = Number(prop);
          const result = adjustBrightness(color, 140 - key);
          // console.log(result);
          return result;
        },
      }) as any as BrandVariants,
    ),
  );
}
watch(isDark, (value) => {
  // 设置 Fluent UI 的主题
  updateTheme(value ? createDarkTheme : createLightTheme);
});
onMounted(() => {
  // 设置 Fluent UI 的主题
  updateTheme(isDark.value ? createDarkTheme : createLightTheme);
});
</script>

<template>
  <fluent-design-system-provider :ref="appProvider">
    <ConfigProvider :locale="antdLocale" :theme="tokenTheme">
      <App>
        <RouterView />
      </App>
    </ConfigProvider>
    <GlobalDialog />
  </fluent-design-system-provider>
</template>
